import OSS from 'ali-oss'
import {updateFile,Get} from "./HttpRequest"
/**
 * 图片上传
 * @param file 文件
 */

interface STSOptions {
    accessKeyId: string
    stsToken: string
    accessKeySecret: string
}

const STSOoptions: STSOptions = {
    accessKeyId: '',
    stsToken: '',
    accessKeySecret: '',
}

let errnums = 0,
    ServiceBusiness = false

/**
 * 图片上传
 * @param {File} file
 * @param {string} name
 * @returns {Promise<unknown>}
 * @constructor
 */
export const AliOSSFileupload = async (file: File, name: string) => {
    return new Promise(async (resolve, reject) => {
        if (!ServiceBusiness && Object.values(STSOoptions).length > 0) {
            const STServer = await Get('https://rwapi.cheeseword.com/v1/Alists/getStsToken',{},{dataAll:true}).catch(err=>{
                console.error(err)
            })
            console.log(STServer, 'STSservei')
            STSOoptions.accessKeyId = STServer.AccessKeyId
            STSOoptions.stsToken = STServer.SecurityToken
            STSOoptions.accessKeySecret = STServer.AccessKeySecret
        }

        const AliYunOSS = new OSS({
            region: 'oss-cn-hangzhou',
            accessKeyId: STSOoptions.accessKeyId, // 'STS.NUnrjUmDehb4zi1NQqm8cNpqk',
            accessKeySecret: STSOoptions.accessKeySecret, //'9u5cTVtnzUT11kujTsQyxDZTtVzanKxuoD6KEbnkov6T1',
            stsToken: STSOoptions.stsToken, // 'CAIS7AF1q6Ft5B2yfSjIr5bbOdDhgJtE36DfeE+AqlEkYbdPobXaiTz2IHFJfHltBewdsfQ3nmFU7/sYlqx6T55OSBQ1ulSTO80Fnzm6aq/t5uaXj9Vd+rDHdEGXDxnkprywB8zyUNLafNq0dlnAjVUd6LDmdDKkLTfHWN/z/vwBVNkMWRSiZjdrHcpfIhAYyPUXLnzML/2gQHWI6yjydBM05lcn0z0guPThmZHMskrk4QekmrNPlePYOYO5asRgBpB7Xuqu0fZ+Hqi7i38Ns0gXqPst0/wco2ab54zHGTlX51CIKe3S7s2/us3iyxCacRqAAZd0ucuu0VqJdqNt+Zo0b9MZ/3rzVWkmnlShIRWU9SJ+9TheH8P0gfOzjtshRCwWFd3MZJraWbIi2IbHEITYBpeixwjXUrpy5h0q49T45DM+VSUlXIw0Pc9N5TG2WbkTbXru39/ry0dzRe5h5oLTNY3VXWI1oqXE+sRrcZhz6izgIAA=',
            bucket: 'recite-words',
        })

        AliYunOSS.multipartUpload('front-course/' + name, file, {})
            .then((res) => {
                ServiceBusiness = true
                console.log(res)
                resolve('https://rwstatic.cheeseword.com/' + res.name)
            })
            .catch((err) => {
                console.error(err)
                errnums++
                ServiceBusiness = false
                if (errnums < 3) {
                    AliOSSFileupload(file,name)
                    console.log(err, '上传错误')
                }
            })
    })
}
